#!/bin/bash

# This file is part of the nxlog log collector tool.
# See the file LICENSE in the source root for licensing terms.
# Website: http://nxlog.org
# Author: Octav Zlatior <octav.zlatior@nxlog.org>

# Timezone macro generation script
# usage:  ./generate_date_macros.sh <source_file.c>

# The script finds time strings in ISO format in a source file
# and generates a "header file" which defines macros of the form:

# 2003-08-24T05:14:15.000003-01:00 =>
# #define TIME_2003_08_24__05_14_15_000003_m01_00 (1061705655000003LL)

# The macro name closely resembles the ISO string, while the value
# equals the corresponding timezone independent UNIX timestamp
# The generated macros will be written to a file <source_file>_header.h

# This script has to be executed manually as a "dev tool"
# and it is not part of the build

IN_FILE=$1
OUT_FILE=${IN_FILE/\.c/_macros.h}

echo "" > $OUT_FILE

MACROS=:

grep -oE "(19|20)[0-9]{2}-((0[1-9])|(1[0-2]))-[0-3][0-9](T| )[0-2][0-9]:[0-5][0-9]:[0-5][0-9][^\"]*" $IN_FILE > generate_date_macros.tmp

while read -r time
do
    line=${time/GMT/gmt}
    line=${line//[ T]/__}
    line=${line/-/_}
    line=${line/-/_}
    line=${line//[:,.]/_}
    line=${line/-/_m}
    line=${line/+/_p}
    line=${line/gmt/GMT}
    line=TIME_$line
    if [[ $MACROS != *:${line}:* ]];
    then
        ts=$(date -u --date="$time" +%s)$(date -u --date="$time" +%N)
        ts=${ts::-3}
        #echo "// ${time}" >> $OUT_FILE
        echo "#define ${line} (${ts}LL)" >> $OUT_FILE
        MACROS+=${line}:
    fi
done < generate_date_macros.tmp
